package com.gzist.elderlyserviceplatform.service;

import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.InputStream;
import java.net.URL;

/**
 * 健康报告邮件服务
 */
@Service
@RequiredArgsConstructor
public class HealthReportEmailService {
    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String senderEmail;
    @Async("emailTaskExecutor")
    public void sendHealthReport(String toEmail, String userName, String reportUrl) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 基础配置
            helper.setFrom(senderEmail);
            helper.setTo(toEmail);
            helper.setSubject(userName + "的健康分析报告");

            // 构建模板内容
            Context context = new Context();
            context.setVariable("userName", userName);
            String htmlContent = templateEngine.process("health-report", context);

            // 添加PDF附件
            URL url = new URL(reportUrl);
            try (InputStream stream = url.openStream()) {
                // 将输入流读取到字节数组
                byte[] bytes = IOUtils.toByteArray(stream);
                helper.addAttachment("health-report.pdf",
                        new ByteArrayResource(bytes),
                        "application/pdf");
            }

            helper.setText(htmlContent, true);
            mailSender.send(message);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("邮件发送失败");
        }
    }
}
